import React, { useRef, useContext, useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Badge, Button, message, Row, Col, Table, Form, InputNumber, Popconfirm, Drawer, Modal } from 'antd';
import ProTable, { ActionType } from '@ant-design/pro-table';
import type { ProColumns } from '@ant-design/pro-table';
import { ProductType, OrderInfo } from '../../../model';
import { DrawerForm, ModalForm, ProFormSelect, ProFormTextArea } from '@ant-design/pro-form';
import ProductChooseForm from '../../../components/Common/ProductChooseForm';
import { Typography, Spin } from 'antd';
import { orderDetailDataById } from '../../Order/service';
import UpDownLabel from '@/components/Common/UpDownLabel';
import { getCurrentDate, manufacturerOption,accSub,accMul,productPropertyOption, priceOption } from '../../../utils/utils';
import { approvalOrderData, onlysave, approveOrder,saveOrderForFinance } from '../service';
import InputDialog from '../../../components/Common/InputDialog';
import { moneyFormat, moneyFormat2 } from '@/utils/utils';
import { Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { RcFile } from 'antd/lib/upload';
import OrderHistory from '@/components/Common/OrderHistory';
const {
  Text
} = Typography;
const EditableContext = React.createContext(null);

const EditableRow = ({
  index,
  ...props
}) => {
  const [form] = Form.useForm();
  return <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props}/>
      </EditableContext.Provider>
    </Form>;
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    // if(record.is_gifts!=0){
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex]
    }); // }
  };

  const save = async () => {
    try {
      const values = await form.validateFields();

      if (values < record.minimum && record.is_gifts == 0) {
        message.warning('不能小于最小起订量：' + record.minimum);
        return;
      }

      toggleEdit();
      handleSave({ ...record,
        ...values
      });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    if (editing) {
      childNode = <Form.Item style={{
        margin: 0
      }} name={dataIndex} rules={[{
        required: true,
        message: `数量必填`
      }]} >
        <InputNumber ref={inputRef} onPressEnter={save} onBlur={save} precision={0}/>
      </Form.Item>;
    } else {
      if (record.is_gifts == 0) {
        childNode = <div style={{
          padding: '4px 12px',
          paddingRight: 24
        }} >
            {children}
          </div>;
      } else {
        if (sessionStorage.getItem('access') === 'checker') {
          childNode = <div style={{
            padding: '4px 12px',
            paddingRight: 24,
            cursor: 'pointer',
            border: '1px solid #d9d9d9',
            borderRadius: '4px'
          }} onClick={toggleEdit} >
              {children}
            </div>;
        } else {
          childNode = <div style={{
            padding: '4px 12px',
            paddingRight: 24
          }} >
              {children}
            </div>;
        }
      }
    }
  }

  return <td {...restProps}>{childNode}</td>;
};

class Order extends React.Component {
  formRef = React.createRef<any>();
  actionRef = React.createRef<ActionType>();
  remarkForm = React.createRef<any>();
  orderHistoryRef:any = React.createRef();

  state:any = {
    activeKey: 'tab1',
    proModalVisible: false,
    detailFlag: false,
    sentArray: [],
    gift: 0,
    newDataSource: [],
    showApprove: false,
    initData: {},
    approveMoney: 0,
    editing: false,
    useMoney: 0,
    spinningFlag: false,
    inputDialog: false,
    status: '0',
    scale: 1,
    dealerCode: '',
    fileList: [],
    showRemark: false,
    editId: '',
    inputFlag: false,
    values: {},
    historyVisible:false,
    editFlag:false
  };
  userInfo: any;

  constructor(props) {
    super(props);
    this.userInfo = {
      'userId': sessionStorage.getItem('userId'),
      'dealerId': sessionStorage.getItem('dealerId')
    };
  }


  editSendColumns: ProColumns<ProductType>[] = [{
    title: '厂家',
    dataIndex: 'manufacturer',
    valueType: 'select',
    width: 80,
    valueEnum: manufacturerOption()
  }, {
    title: '产品名称',
    dataIndex: 'product_name',
    ellipsis: true,
    renderText: (_, record: any) => {
      if (record.is_gifts == 1) {
        return `${record.product_name}(赠品)`;
      }

      return record.product_name;
    },
  }, {
    title: '产品型号',
    ellipsis: true,
    dataIndex: 'product_standard',
  }, {
    title: '产品性质',
    dataIndex: 'product_standard',
    width: 150,
    renderText:()=>'生产产品'
  }, {
    title: '单位',
    dataIndex: 'packing_unit',
    width: 80,
    ellipsis:true,
  }, {
    title: '订货数量',
    dataIndex: 'numbs',
    width: 80
  }, {
    title: '',
    dataIndex: 'numbs2',
    width: 70,
    renderText:()=>' '
  }, {
    title: '单价(元)',
    dataIndex: 'standard_price',
    width: 150,
    renderText: (_, record: any) => {
      if (record.is_gifts == 1) {
        return `0`;
      }

      if (record.unit_price && Number(record.unit_price) != Number(record.standard_price)) {
        return <>{moneyFormat(record.standard_price)}<span style={{
            textDecoration: 'line-through',
            color: '#d1d1d1',
            marginLeft: 10
          }}>{moneyFormat(record.unit_price)}</span></>;
      }

      return moneyFormat(record.standard_price);
    }
  }, {
    title: '已发货',
    dataIndex: 'send_numbs',
    width: 100
  }, {
    title: '金额(元)',
    dataIndex: 'actual_amount',
    width: 200,
    align: 'left',
    renderText: (_, record: any) => {
      if (record.is_gifts == 1) {
        return `0`;
      }

      return moneyFormat(accMul(Number(record.standard_price), record.send_numbs));
    }
  }];
  
  renderBadge = (count: number, active = false) => {
    return <Badge count={count} style={{
      marginTop: -2,
      marginLeft: 4,
      color: active ? '#1890FF' : '#999',
      backgroundColor: active ? '#E6F7FF' : '#eee'
    }} />;
  };
  columns: ProColumns<OrderInfo>[] = [{
    title: '厂家',
    dataIndex: 'manufacturer',
    valueType: 'select',
    valueEnum: manufacturerOption()
  },{
    title: '订单号',
    dataIndex: 'order_number'
  }, {
    title: '客户代码',
    dataIndex: 'dealerCode'
  }, {
    title: '客户名称',
    dataIndex: 'dealerName'
  }, {
    title: '订货日期',
    dataIndex: 'order_time',
    hideInSearch: true
  }, {
    title: '交货日期',
    dataIndex: 'delivery_time',
    hideInSearch: true
  }, {
    title: '订货日期',
    valueType: 'dateRange',
    dataIndex: 'date',
    hideInTable: true
  }, {
    title: '订单金额',
    dataIndex: 'actual_amount',
    hideInSearch: true,
    valueType: 'money'
  }, {
    title: '审核备注',
    dataIndex: 'opinion',
    hideInSearch: true
  },  {
    title: '操作',
    key: 'option',
    width: 130,
    valueType: 'option',
    render: (_, record,index) => {
      if(index%2==0){
        return [<a key='show' onClick={() => {
          this.detail(record)
          this.setState({editFlag:true})
        }}>详情</a>,<a key='show' onClick={() => {
          this.setState({historyVisible:true})
          this.orderHistoryRef.current?.init('id')
        }}>改单记录</a>]
      }
      return [<a key='show' onClick={() => {
        this.detail(record)
        this.setState({editFlag:false})
      }}>详情</a>]
    },
  }];
  viewPcolumns: ProColumns<ProductType>[] = [{
    title: '厂家',
    dataIndex: 'manufacturer',
    valueType: 'select',
    width: 80,
    valueEnum: manufacturerOption()
  }, {
    title: '产品名称',
    dataIndex: 'product_name',
    ellipsis:true,
    renderText: (_, record: any) => {
      if (record.is_gifts == 1) {
        return `${record.product_name}(赠品)`;
      }

      return record.product_name;
    }
  }, {
    title: '产品型号',
    dataIndex: 'product_standard'
  }, {
    title:'产品性质',
    dataIndex: 'productProperty',
    width:150,
    valueType:'select',
    valueEnum:productPropertyOption(),
  }, {
    title: '单位',
    width: 80,
    ellipsis:true,
    dataIndex: 'packing_unit'
  }, {
    title: '订货数量',
    width: 80,
    dataIndex: 'numbs'
  }, {
    title: '合计',
    dataIndex: 'numbs_count',
    width: 70,
    colSpan: 1,
    align: 'center',
    render: (value: any, record: any) => {
      const obj = {
        children: value,
        props: {}
      };
      obj.props.rowSpan = record.name_count;
      return obj;
    }
  }, {
    title: '单价(元)',
    dataIndex: 'standard_price',
    width: 160,
    render: (_: any, record: any) => {
      if (record.is_gifts == 0) {
        if (record.unit_price && Number(record.unit_price) != Number(record.standard_price)) {
          return <>{moneyFormat(accMul(Number(record.standard_price) , this.state.scale))}<span style={{
              textDecoration: 'line-through',
              color: '#d1d1d1',
              marginLeft: 10
            }}>{moneyFormat(Number(record.unit_price))}</span></>;
        } else {
          let val: number = accMul(Number(record.standard_price) , this.state.scale);
          return moneyFormat(val);
        }
      } else {
        return moneyFormat(0);
      }
    }
  },{
    title: '价格等级',
    width: 100,
    align: 'left',
    renderText:(val:string)=>{
      if(!val){
        return '-'
      }
      if(priceOption()[val]){
        return priceOption()[val].text
      }
      return '自定义'
    },
    dataIndex: 'sort'
  }, {
    title: '金额(元)',
    valueType: 'money',
    width: 130,
    align: 'left',
    dataIndex: 'actual_amount'
  }, {
    title: '备注',
    dataIndex: 'remarks',
    width: 100,
    ellipsis: true
  }];

  async detail(record: any) {
    this.setState({
      spinningFlag: true
    });
    var param: any = {
      orderId: record.id
    };
    var val = await orderDetailDataById(param);

    if (val.errorCode === '200') {
      //如果是待审核
      if (this.state.activeKey === 'tab1') {
        //获取下收货列表
        val.data.list.forEach((item: any) => {
          item.id = item.productId;
        });
        this.setState({
          dealerCode: record.dealerCode,
          showApprove: true,
          initData: val.data,
          newDataSource: val.data.list,
          currentDay: getCurrentDate(),
          approveMoney: val.data.order?.total
        }); //初始化数据
      } else {
        this.setState({
          dealerCode: record.dealerCode,
          detailFlag: true,
          initData: val.data
        });
      }

      this.setState({
        fileList: val.data.attList
      });
    } else {
      message.error('获取订单详情失败');
    }

    this.setState({
      spinningFlag: false
    });
  }

  showSentInfo() {}

  formItemLayout = {
    labelCol: {
      span: 6
    },
    wrapperCol: {
      span: 16
    }
  };
  pColumns = [{
    title: '厂家',
    dataIndex: 'manufacturer',
    valueType: 'select',
    width: 80,
    valueEnum: manufacturerOption()
  }, {
    title: '产品名称',
    dataIndex: 'product_name',
    key: 'product_name',
    renderText: (_, record: any) => {
      if (record.is_gifts == 1) {
        return `${record.product_name}(赠品)`;
      }

      return record.product_name;
    }
  }, {
    title: '产品型号',
    dataIndex: 'product_standard',
    key: 'product_standard'
  },
   {
    title:'产品性质',
    dataIndex: 'productProperty',
    width:150,
    valueType:'select',
    valueEnum:productPropertyOption(),
  }, 
  {
    title: '单位',
    dataIndex: 'packing_unit',
    key: 'packing_unit',
    width: 80,
    ellipsis:true,
  }, {
    title: '数量',
    dataIndex: 'numbs',
    editable: true,
    width: 80,
    key: 'numbs'
  }, {
    title: '合计',
    dataIndex: 'numbs_count',
    width: 70,
    colSpan: 1,
    align: 'center',
    render: (value: any, record: any) => {
      const obj = {
        children: value,
        props: {}
      };
      obj.props.rowSpan = record.name_count;
      return obj;
    }
  }, {
    title: '单价(元)',
    valueType: 'money',
    width: 150,
    dataIndex: 'standard_price',
    render: (_, record: any) => {
      if (record.is_gifts == 0) {
        if (record.unit_price && Number(record.unit_price) != Number(record.standard_price)) {
          return <>{moneyFormat(accMul(Number(record.standard_price) , this.state.scale))}<span style={{
              textDecoration: 'line-through',
              color: '#d1d1d1',
              marginLeft: 10
            }}>{moneyFormat(Number(record.unit_price))}</span></>;
        } else {
          let val: number = accMul(Number(record.standard_price) , this.state.scale);
          return moneyFormat(val);
        }
      } else {
        return moneyFormat(0);
      }
    }
  },{
    title: '价格等级',
    width: 100,
    align: 'left',
    dataIndex: 'sort',
    renderText:(val:string)=>{
      if(!val){
        return '-'
      }
      if(priceOption()[val]){
        return priceOption()[val].text
      }
      return '自定义'
    },
  }, {
    title: '金额(元)',
    valueType: 'money',
    key: 'money',
    align: 'left',
    width: 100,
    renderText: (_, record: any) => {
      let val: number = record.standard_price * record.numbs * (record.is_gifts == 1 ? 0 : 1 * this.state.scale);
      return val;
    }
  }, {
    title: '操作',
    width:100,
    valueType: 'option',
    hideInTable: sessionStorage.getItem('access') === 'checker' ? false : true,
    render: (_: any, record: any) => this.state.newDataSource.length >= 1 ? [<a key='remark' onClick={() => {
      this.remarkForm.current?.setFieldsValue({
        remarks: record.remarks
      });
      this.setState({
        showRemark: true,
        editId: record.id + '_' + record.is_gifts
      });
    }}>备注</a>, <Popconfirm title='确定删除该产品吗?' onConfirm={() => {
      if (record.is_gifts != 1) {
        message.warning('非赠品不支持删除');
        return;
      }

      this.handleDelete(record.id + '_' + record.is_gifts);
    }} >
            <a>删除</a>
          </Popconfirm>] : null
  }];
  prepare = (newDS: any) => {
    newDS.sort((a: any, b: any) => {
      if (a.product_name === b.product_name) {
        return a.is_gifts - b.is_gifts;
      }

      return a.product_name < b.product_name ? -1 : 1;
    });
    var nameMap = {};
    newDS.forEach((item: any) => {
      var key = `${item.product_name}_${item.is_gifts}`;

      if (nameMap[key] !== undefined) {
        nameMap[key].numbs = nameMap[key].numbs + item.numbs;
        nameMap[key].count = nameMap[key].count + 1;
      } else {
        nameMap[key] = {
          numbs: item.numbs,
          count: 1
        };
      }
    });
    newDS.forEach((item: any) => {
      var key = `${item.product_name}_${item.is_gifts}`;

      if (nameMap[key] != undefined) {
        //第一次出现
        item.numbs_count = nameMap[key].numbs;
        item.name_count = nameMap[key].count; //移除掉

        nameMap[key] = undefined;
      } else {
        item.numbs_count = '';
        item.name_count = 0;
      }
    });
    this.setState({
      newDataSource: [...newDS]
    });
  };
  handleDelete = (id: any) => {
    var newData = this.state.newDataSource.filter((item: any) => item.id + '_' + item.is_gifts !== id); // this.setState({newDataSource:newData});

    this.prepare(newData);
  };
  handleSave = (row: any) => {
    const index = this.state.newDataSource.findIndex((item: any) => row.id + '_' + row.is_gifts === item.id + '_' + item.is_gifts);
    const item = this.state.newDataSource[index];
    this.state.newDataSource.splice(index, 1, { ...item,
      ...row
    }); // let newDS=[...this.state.newDataSource]

    this.prepare(this.state.newDataSource);
  };
  approve = async (values: any) => {
    var val = await approveOrder(values);

    if (val.errorCode === '200') {
      message.success('提交成功');
      this.actionRef.current?.reloadAndRest?.();
      return true;
    } else {
      message.error(val.errorMessage);
      return false;
    }
  };
  saveOrder = async (values: any, opinion: string) => {
    var param: any = {
      order: {},
      product: []
    };
    param.order.id = this.state.initData.order?.id;
    param.order.total = this.state.approveMoney;
    param.order.use_rebate = this.state.initData.order?.use_rebate;
    param.order.actual_amount = accSub(accSub(this.state.approveMoney ,this.state.initData.order?.use_rebate), this.state.initData.order?.discount);
    param.order.discount = this.state.initData.order?.discount;
    param.order.payment_method = values.payment_method;
    param.order.postPayMethod = values.postPayMethod;
    param.order.remarks = values.remarks;
    param.order.opinion = '';
    var flag = false;

    for (var i = 0; i < this.state.newDataSource.length; i++) {
      if (this.state.newDataSource[i].is_gifts == 1 && this.state.newDataSource[i].numbs <= 0) {
        flag = true;
        break;
      }
    }

    if (flag) {
      message.warning('赠品数量需大于0');
      return false;
    }

    if (this.state.approveMoney - this.state.initData?.order?.use_rebate <= 0) {
      message.warning('订单金额必须大于0');
      return false;
    }

    this.state.newDataSource.forEach((item: any) => {
      var p: any = {
        remarks: item.remarks,
        productId: item.id,
        numbs: item.numbs,
        sort:item.sort,
        is_gifts: item.is_gifts,
        standard_price: accMul(accMul(item.standard_price , this.state.scale), (item.is_gifts == 1 ? 0 : 1)),
        discount: accMul(this.state.scale , (item.is_gifts == 1 ? 0 : 1)),
        actual_amount: accMul(accMul(item.standard_price , item.numbs),accMul( this.state.scale , (item.is_gifts == 1 ? 0 : 1)))
      };

      if (item.unit_price) {
        p.unit_price = item.unit_price;
      }

      param.product.push(p);
    });
    var val = await onlysave(param);
    if (val.errorCode === '200') {
      return this.approve({
        isPass: 1,
        orderId: param.order.id,
        opinion: opinion
      });
    } else {
      message.error(val.errorMessage);
      return false;
    }
  };
  handlePreview = async (file: any) => {
    window.open(file.url);
  };

  render() {
    const components = {
      body: {
        row: EditableRow,
        cell: EditableCell
      }
    };
    const columns = this.pColumns.map(col => {
      if (!col.editable) {
        return col;
      }

      return { ...col,
        onCell: (record: any) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave
        })
      };
    });
    const uploadProps = {
      name: 'file',
      accept: 'image/*,application/pdf',
      action: '/xwyl/attachment/uploadAttach',
      headers: {
        authorization: 'authorization-text'
      },
      beforeUpload: (file: RcFile, FileList: RcFile[]) => {
        var flag = file.type.indexOf('pdf') >= 0;

        if (!flag) {
          message.error('请上传图片格式或pdf格式');
        }

        return flag;
      }
    };
    return <>
    <PageContainer>
    <ProTable<OrderInfo>  scroll={{x:1200}} columns={this.columns} actionRef={this.actionRef} request={async (params, sorter, filter) => {
          var other = {
            isPass: this.state.status
          };

          if (params.date) {
            params.beginDate = params.date[0];
            params.endDate = params.date[1];
            params.date = undefined;
          }

          return approvalOrderData({ ...params,
            filter,
            ...other
          });
        }} search={{
          span: 6
        }} toolbar={{
          menu: {
            type: 'tab',
            activeKey: this.state.activeKey,
            items: [{
              key: 'tab1',
              label: <span>待处理{this.renderBadge(0, this.state.activeKey === 'tab1')}</span>
            }, {
              key: 'tab2',
              label: <span>已处理{this.renderBadge(0, this.state.activeKey === 'tab2')}</span>
            }],
            onChange: key => {
              var status = 0;

              if (key === 'tab1') {
                status = 0;
              } else if (key === 'tab2') {
                status = 1;
              }

              this.setState({
                activeKey: (key as string),
                status: status
              });
              this.actionRef.current?.reloadAndRest?.();
            }
          },
          actions: undefined,
          settings: []
        }} rowKey='id' pagination={{
          pageSizeOptions: ['20', '100', '500']
        }} dateFormatter='string'/>
    <Drawer width={1250} title={'详情'} visible={this.state.detailFlag} onClose={() => {
          this.setState({ 
            detailFlag: false,
            initData: {}
          });
        }} >
        <Row style={{
            marginLeft: '22px'
          }} >
            <Col span={5}><UpDownLabel title='订单号' texts={[this.state.initData?.order?.order_number]} /></Col>
            <Col span={5}><UpDownLabel title='客户代码' texts={[this.state.dealerCode]} /></Col>
            <Col span={5}><UpDownLabel title='客户名称' texts={[this.state.initData?.order?.dealerName]} /></Col>
            <Col span={5}><UpDownLabel title='订货日期' texts={[this.state.initData?.order?.order_time]} /></Col>
            <Col span={4}><UpDownLabel title='交货日期'	 texts={[this.state.initData?.order?.delivery_time]} /></Col>
          </Row>
          <Row style={{
            marginLeft: '22px'
          }}>
            <Col span={5}><UpDownLabel title='付款方式' texts={[this.state.initData?.order?.payment_method]} /></Col>
            <Col span={5}><UpDownLabel title='运费方式' texts={[this.state.initData?.order?.postPayMethod]} /></Col>
            <Col span={5}><UpDownLabel title='销售' texts={[this.state.initData?.order?.salesName]} /></Col>
            <Col span={5}><UpDownLabel title='收货人' texts={[this.state.initData?.order?.consignee]} /></Col>
            <Col span={4}><UpDownLabel title='收货电话' texts={[this.state.initData?.order?.mobile]} /></Col>
          </Row>

        <Row style={{
            marginLeft: '22px'
          }} >
          <Col span={8} ><UpDownLabel title='收货地址' texts={[this.state.initData?.order?.provinces_label + this.state.initData?.order?.city_label + this.state.initData?.order?.area_label + ' - ' + this.state.initData?.order?.delivery_address]}  /></Col>
          <Col span={2}></Col>
          <Col span={8} ><UpDownLabel title='出库单地址' texts={[this.state.initData?.order?.realAddress]}  /></Col>
          <Col span={6}></Col>
        </Row>
        <ProTable<ProductType> scroll={{x:1200}} headerTitle='订单产品' toolbar={{
            settings: []
          }} columns={this.viewPcolumns} dataSource={this.state.initData?.list} rowKey='id' size='small' pagination={false} search={false} summary={pageData => {
            return <>  
                  <Table.Summary.Row >
                    <Table.Summary.Cell index={1} colSpan={6} >总金额:</Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1} align='center' >
                       {this.state.initData?.list?.reduce(function (total, currentValue, currentIndex, arr) {
                    return currentValue['numbs'] ? total + currentValue['numbs'] : total;
                  }, 0)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left' colSpan={2}>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left' colSpan={2}>
                      ￥{moneyFormat(this.state.initData?.order?.total)}
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                  <Table.Summary.Row >
                    <Table.Summary.Cell index={1} colSpan={9} >优惠金额:</Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left' >
                    ￥{moneyFormat(this.state.initData?.order?.discount)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1}  />
                  </Table.Summary.Row>
                  <Table.Summary.Row >
                    <Table.Summary.Cell index={1} colSpan={9} >返利金额:</Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left' >
                    ￥{moneyFormat(this.state.initData?.order?.use_rebate)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1}  />
                  </Table.Summary.Row>
                  <Table.Summary.Row >
                    <Table.Summary.Cell index={1} colSpan={9} >
                    <Text >实付金额：</Text>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left' >
                    ￥{moneyFormat(this.state.initData?.order?.actual_amount)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1}  />
                  </Table.Summary.Row>
                </>;
          }} >
        </ProTable>
        <Row style={{
            margin: '22px'
          }}>
            <Col span={24} ><UpDownLabel title='备注' texts={[this.state.initData?.order?.remarks]} /></Col>
            {/* <Col span={24} ><UpDownLabel title='审核备注' texts={[this.state.initData?.order?.opinion]}/></Col> */}
        </Row>
      </Drawer>
      <DrawerForm title='审核订单' width={1250} drawerProps={{
          destroyOnClose: true
        }} formRef={this.formRef} onVisibleChange={val => {
          this.setState({
            showApprove: val
          });

          if (!val) {
            this.setState({
              newDataSource: [],
              scale: 1
            });
          }
        }} visible={this.state.showApprove} onFinish={async (values: any) => {
          this.setState({
            inputDialog: true,
            inputFlag: false,
            values: values
          });
          return false;
        }} submitter={{
          searchConfig: {
            submitText: '审核通过',
            resetText: '取消'
          },
          render: (props, defaultDoms) => {
            return [...defaultDoms, <Button danger key='back' onClick={() => {
              this.setState({
                inputDialog: true,
                inputFlag: true
              });
            }}  >
                  退回
                </Button>];
          }
        }} layout='horizontal' labelAlign='left' {...this.formItemLayout} >
          <Row gutter={5}>
            <Col span={4}><UpDownLabel title='订单号' texts={[this.state.initData?.order?.order_number]}  /></Col>
            <Col span={4}><UpDownLabel title='销售' texts={[this.state.initData?.order?.salesName]}  /></Col>
            <Col span={8}><UpDownLabel title='收货地址' texts={[this.state.initData?.order?.provinces_label + this.state.initData?.order?.city_label + this.state.initData?.order?.area_label + ' - ' + this.state.initData?.order?.delivery_address]}  /></Col>
            <Col span={4}><UpDownLabel title='收货人' texts={[this.state.initData?.order?.consignee]}  /></Col>
            <Col span={4}><UpDownLabel title='收货电话' texts={[this.state.initData?.order?.mobile]}  /></Col>
          </Row>
          <Row >
           
               {
                 !this.state.editFlag?
                 <Col span={8} > <ProFormSelect name='payment_method' label='付款方式' initialValue={this.state.initData?.order?.payment_method} options={[{
                  label: '预付',
                  value: '预付'
                }, {
                  label: '赊账',
                  value: '赊账'
                },{
                  label: '部分赊账',
                  value: '部分赊账'
                }]} rules={[{
                  required: true
                }]}  />  </Col> : <Col span={4} ><UpDownLabel title='付款方式' texts={['预付']}  /></Col>
               }
            <Col span={4} >
              <UpDownLabel title='客户代码' texts={[this.state.dealerCode]}  />
            </Col>
            <Col span={this.state.editFlag?8:4} >
              <UpDownLabel title='客户名称' texts={[this.state.initData?.order?.dealerName]}  />
            </Col>
            <Col span={4} >
              <UpDownLabel title='订货日期' texts={[this.state.initData?.order?.order_time]}  />
            </Col>
            <Col span={4} >
              <UpDownLabel title='交货日期' texts={[this.state.initData?.order?.delivery_time]}  />
            </Col>
          </Row>
          <Row >
           
            {
                 !  this.state.editFlag?
                 <Col span={8} ><ProFormSelect name='postPayMethod' label='运费方式' initialValue={this.state.initData?.order?.postPayMethod} options={[{
                label: '寄付',
                value: '寄付'
              }, {
                label: '到付',
                value: '到付'
              }]} rules={[{
                required: true
              }]}  />     </Col>:   <Col span={4} ><UpDownLabel title='运费方式' texts={['寄付']}  />     </Col>
            }
       
            <Col span={16} >
              <UpDownLabel title='出库单地址' texts={[this.state.initData?.order?.realAddress]}  />
            </Col>
          </Row>
          {
            this.state.editFlag?<>
             <div style={{fontSize:16,fontWeight:'bold',marginTop:10,marginBottom:10}}>已发货产品</div>
            <ProTable<ProductType> size='small' toolbar={{
              settings: []
            }} columns={this.editSendColumns} dataSource={this.state.newDataSource} rowKey={(record: ProductType) => record.id + '_' + record.is_gifts} pagination={false} search={false} toolBarRender={false}>
            </ProTable>
          </>:<></>
          }
          <div style={{fontSize:16,fontWeight:'bold',marginTop:10,marginBottom:10}}>订单产品</div>
          <ProTable<ProductType> rowKey={(record: ProductType) => record.id + '_' + record.is_gifts} components={components} pagination={false} size='small' dataSource={this.state.newDataSource} search={false} toolBarRender={false} columns={columns} summary={pageData => {
            return sessionStorage.getItem('access') === 'checker' ? <>
                   <Table.Summary.Row >
                    <Table.Summary.Cell index={1} colSpan={6} >
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='center' >
                        {this.state.newDataSource.reduce(function (total, currentValue, currentIndex, arr) {
                    return currentValue['numbs'] ? total + currentValue['numbs'] : total;
                  }, 0)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1} >
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left' colSpan={3} >
                      {true ? <Button type='primary' onClick={() => {
                    this.setState({
                      gift: 1,
                      proModalVisible: true
                    });
                  }} >
                        选择赠品
                      </Button> : {}}
                     
                    </Table.Summary.Cell>
                  
                  </Table.Summary.Row>
                  <Table.Summary.Row >
                    <Table.Summary.Cell index={1} colSpan={8} >总金额：</Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1} />
                    <Table.Summary.Cell index={1} colSpan={2} align='left' >
                      {
                    /* <InputNumber onBlur={(node)=>{
                    var oriTotal = this.state.initData.order?.total;
                    var scale = Number(node.target.value)/oriTotal;
                    this.setState({approveMoney:Number(node.target.value),scale:scale})
                    }} placeholder=请输入 name=approveMoney  precision={0} defaultValue={this.state.approveMoney} />元 */
                  }
                      ￥{moneyFormat(this.state.initData?.order?.total)}
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={1} colSpan={9} >
                      <span>优惠金额：</span>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left' >
                    ￥{moneyFormat2(this.state.initData?.order?.discount)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1}  />
                  </Table.Summary.Row>
                  <Table.Summary.Row >
                    <Table.Summary.Cell index={1} colSpan={9} >
                      <span>返利金额：</span>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left' >
                    ￥{moneyFormat2(this.state.initData?.order?.use_rebate)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1}  />
                  </Table.Summary.Row>
                  <Table.Summary.Row >
                    <Table.Summary.Cell index={1} colSpan={9} >
                      <span>实付金额：</span>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left' >
                    ￥{this.state.initData?.order?.discount ? moneyFormat(this.state.approveMoney - this.state.initData?.order?.discount - this.state.initData?.order?.use_rebate) : moneyFormat(this.state.approveMoney - this.state.initData?.order?.use_rebate)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1}  />
                  </Table.Summary.Row>
                </> : <>
                  <Table.Summary.Row >
                    <Table.Summary.Cell index={1} colSpan={6} >总金额：</Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1} align='center' >
                       {this.state.initData?.list?.reduce(function (total, currentValue, currentIndex, arr) {
                    return currentValue['numbs'] ? total + currentValue['numbs'] : total;
                  }, 0)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left' colSpan={2}>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left' colSpan={1}>
                    ￥{moneyFormat(this.state.initData?.order?.total)}
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                  <Table.Summary.Row >
                    <Table.Summary.Cell index={1} colSpan={9} >优惠金额：</Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left' >
                    ￥{moneyFormat2(this.state.initData?.order?.discount)}
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                  <Table.Summary.Row >
                    <Table.Summary.Cell index={1} colSpan={9} >返利金额：</Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left' >
                    ￥{moneyFormat2(this.state.initData?.order?.use_rebate)}
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                  <Table.Summary.Row >
                    <Table.Summary.Cell index={1} colSpan={9} >
                      <span >实付金额：</span>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left' >
                    ￥{moneyFormat(this.state.initData?.order?.actual_amount)}
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                </>;
          }}  />
     <Row style={{
            margin: '22px 0'
          }}>
        <Upload {...uploadProps} fileList={this.state.fileList} onPreview={this.handlePreview} showUploadList={{
              showRemoveIcon: false
            }} data={{
              'shipId': this.state.initData?.order?.id,
              'clear': 1,
              'userId': sessionStorage.getItem('userId')
            }} headers={{
              'authorization': `${sessionStorage.getItem('token')}`
            }} onChange={(info: any) => {
              if (info.file.status === 'done') {
                if (info.file.response.errorCode === '200') {
                  // var fileList:any[] = this.state.fileList;
                  var fileList: any[] = [];
                  message.success(`${info.file.name}上传成功`);
                  var data = info.file.response.data;
                  data.uid = data.attId;
                  data.name = info.file.name;
                  data.url = data.location;
                  data.status = 'done';
                  fileList.push(data);
                  this.setState({
                    fileList: [...fileList]
                  });
                } else {
                  message.error(`${info.file.name} 上传失败.`);
                }
              } else if (info.file.status === 'error') {
                message.error(`${info.file.name} 上传失败.`);
              }
            }}>
            <Button icon={<UploadOutlined/>}><span style={{
                  color: '#ff0000'
                }}>*</span>上传订货合同</Button>
        </Upload>
        </Row>
          <Row style={{
            margin: '22px 0'
          }}>
            <Col span={24} >
                <ProFormTextArea name='remarks' initialValue={this.state.initData?.order?.remarks} placeholder={'请填写备注'} label='备注：' fieldProps={{
                showCount: true,
                maxLength: 500
              }}  />
            </Col>
            {/* {this.state.initData?.order?.opinion ? <Col span={24} ><UpDownLabel title='审核备注' texts={[this.state.initData?.order?.opinion]} /></Col> : <a key='o'></a>} */}
          </Row>
         </DrawerForm>
         <ProductChooseForm self={true} dealerId={this.state.initData?.order?.dealerId} onCancel={() => {
          this.setState({
            proModalVisible: false
          });
        }} onSubmit={async (value: ProductType[]) => {
          value.forEach((item:any)=>{
            item.sort = item.rownum
          })
          var dataSource = [...this.state.newDataSource, ...value];
          this.setState({
            proModalVisible: false
          });
          this.prepare(dataSource);
        }} modalVisible={this.state.proModalVisible} values={this.state.newDataSource} gift={this.state.gift} admin={true}/>
         <InputDialog inputFlag={true} onCancel={() => {
          this.setState({
            inputDialog: false
          });
        }} onSubmit={async value => {
          var data = value[0];
          this.setState({
            showApprove: false,
            inputDialog: false
          });
          if (!this.state.inputFlag) {
            if (sessionStorage.getItem('access') === 'checker') {
              this.saveOrder(this.state.values, data);
            } else {
              var param: any = {
                id:this.state.initData.order?.id,
                payment_method:this.state.values.payment_method,
                postPayMethod:this.state.values.postPayMethod,
                remarks: this.state.values.remarks
              };
              var val = await saveOrderForFinance(param);
              if (val.errorCode === '200') {
                //直接审核
                this.approve({
                  isPass: 1,
                  orderId: this.state.initData.order?.id,
                  opinion: data
                });
              } else {
                message.error(val.errorMessage);
              }
            }
          } else {
            var flag = this.approve({
              isPass: 2,
              orderId: this.state.initData.order?.id,
              opinion: data
            });

            if (flag) {
              this.setState({
                showApprove: false,
                inputDialog: false
              });
            } else {
              this.setState({
                inputDialog: false
              });
            }
          }
        }} inputFlag={this.state.inputFlag} modalVisible={this.state.inputDialog} title='审核意见' label='审核意见' placeholder='请填写审核意见' >
        </InputDialog>
          <ModalForm title='设置产品备注' formRef={this.remarkForm} visible={this.state.showRemark} onVisibleChange={flag => {
          this.setState({
            showRemark: flag
          });
        }} modalProps={{
          forceRender: true,
          destroyOnClose: true
        }} onFinish={async values => {
          for (var i = 0; i < this.state.newDataSource.length; i++) {
            if (this.state.newDataSource[i].id + '_' + this.state.newDataSource[i].is_gifts === this.state.editId) {
              this.state.newDataSource[i].remarks = values.remarks;
              break;
            }
          }

          this.setState({
            newDataSource: this.state.newDataSource
          });
          return true;
        }} >
                <ProFormTextArea name='remarks' label='产品备注' width='xl' />
          </ModalForm>

          <Modal  title=""
        width={'90%'}
        footer={false}
        destroyOnClose={true}
        visible={this.state.historyVisible}
        onCancel={()=>{
            this.setState({historyVisible:false})
        }}
       >
          <OrderHistory  ref={this.orderHistoryRef}></OrderHistory>
       </Modal>

         <Spin spinning={this.state.spinningFlag} style={{
          transform: 'translate(-50%,-50%)',
          left: '50%',
          top: '50%',
          position: 'absolute'
        }} />
    </PageContainer>
    </>;
  }

}

export default Order;